﻿namespace Compass.Wpf;

/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : PrismApplication
{
    //依赖注入容器：private readonly IContainerProvider _provider;
    protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        containerRegistry.RegisterRestSharp();

        containerRegistry.RegisterPageApiService();

        containerRegistry.RegisterDataApiService();

        containerRegistry.RegisterPageViewModel();

        containerRegistry.RegisterDataViewModel();

        containerRegistry.RegisterDialogViewModel();

        containerRegistry.RegisterAutoDrawingService();
    }

    #region 当tab键获得焦点时textbox 全选
    //https://www.cnblogs.com/jane850113/p/6943703.html
    protected override void OnStartup(StartupEventArgs e)
    {
        EventManager.RegisterClassHandler(typeof(TextBox), TextBox.GotFocusEvent, new RoutedEventHandler(TextBox_GotFocus));
        base.OnStartup(e);
    }

    private void TextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        (sender as TextBox).SelectAll();
    }
    #endregion

    #region 初始化与登录
    protected override Window CreateShell()
    {
        return Container.Resolve<MainView>();
    }

    /// <summary>
    /// 初始化时跳转登录页面，并配置默认启动页
    /// </summary>
    protected override void OnInitialized()
    {
        var dialog = Container.Resolve<IDialogService>();
        //程序启动时首先启动登录窗口
        dialog.ShowDialog("LoginView", callback =>
        {
            if (callback.Result != ButtonResult.OK)
            {
                Application.Current.Shutdown();
                return;
            }
            //配置默认首页,在应用程序设置中，启动默认首页。
            var service = Current.MainWindow!.DataContext as IConfigureService;
            service!.Configure();
            base.OnInitialized();
        });
    }

    /// <summary>
    /// 退出登录
    /// </summary>
    /// <param name="containerProvider"></param>
    public static void Logout(IContainerProvider containerProvider, IRegionManager regionManager)
    {

        Current.MainWindow.Hide();
        var dialog = containerProvider.Resolve<IDialogService>();
        dialog.ShowDialog("LoginView", callback =>
        {
            if (callback.Result != ButtonResult.OK)
            {
                Environment.Exit(0);
                return;
            }
            Current.MainWindow.Show();
            //显示页面后重新加载一次Index，以更新界面显示
            regionManager.Regions[PrismManager.MainViewRegionName].RequestNavigate("IndexView", back =>
            {
                var journal = back.Context.NavigationService.Journal;
            });
        });
    }
    #endregion
}